/**
 * 
 */
package com.security.frame.core.controller;

import com.security.frame.core.code.ValidateCodeProcessorHolder;
import com.security.frame.core.common.CommonConstants;
import com.security.frame.core.common.CommonResponse;
import com.security.frame.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.security.frame.core.code.ValidateCodeProcessor;

/**
 * 请求处理
 *
 * @author wangjie
 * @version V1.0
 * @date 2019/11/4
 */
@RestController
@Slf4j
public class SecurityController {

	private RequestCache requestCache = new HttpSessionRequestCache();

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

	@Autowired
	private ValidateCodeProcessorHolder validateCodeProcessorHolder;

	@Autowired
	private ProviderSignInUtils providerSignInUtils;

	/**
	 * 创建验证码，根据验证码类型不同，调用不同的 {@link ValidateCodeProcessor}接口实现
	 *
	 * @param request
	 * @param response
	 * @param type
	 * @throws Exception
	 */
	@GetMapping(CommonConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{type}")
	public void createCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type)
			throws Exception {
		log.info("【发送{}验证码】",type);
		validateCodeProcessorHolder.findValidateCodeProcessor(type).create(new ServletWebRequest(request, response));
	}

	/**
	 * 当需要身份认证时，跳转到这里
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(CommonConstants.DEFAULT_UNAUTHENTICATION_URL)
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public void requireAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
			redirectStrategy.sendRedirect(request, response, securityProperties.getCommon().getLoginPage());


	}

	@PostMapping("/user/regist")
	public CommonResponse regist(String username, HttpServletRequest request) {

		//不管是注册用户还是绑定用户，都会拿到一个用户唯一标识。
		String userId = username;
		providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
		return new CommonResponse("注册成功！");
	}

}
